import axios from 'axios'
import {Message} from 'element-ui'
import router from '../router'
import config from "../config"
// 创建axios 实例
const service = axios.create({

  baseURL: config.baseUrl, // api的base_url
  // baseURL: process.env.VUE_APP_BASE_API, // api的base_url
  timeout: 10000 // 请求超时时间
})
service.defaults.headers.post['Content-Type'] = 'application/json'
// http request 拦截器
service.interceptors.request.use(
  config => {
    if (localStorage.token) config.headers['Authorization'] = localStorage.getItem('token')
    return config
  },
  error => {
    return Promise.reject(error)
  }
)

// http response 拦截器
service.interceptors.response.use(
  response => {
    return response.data
  },
  error => {
    if (error.response) {
      switch (error.response.status) {
        case 401:
          Message({
            type: 'error',
            message: '登录失效！请重新登录'
          })
          localStorage.clear();
          router.push('/login')
          break
        case 404:
          Message({
            showClose: true,
            message: error.response.statusText,
            type: 'error'
          })
          break
        default:
          break
      }
    }
    return Promise.reject(error && error.response)
  }
)

export default service

